import {Component} from "react";
import Button from '../Button'
import PropTypes from 'prop-types'
import {sortBy} from 'lodash'
import Sort from '../Sort'

const SORTS = {
    NONE: list => list,
    TITLE: list => sortBy(list, 'title'),
    AUTHOR: list => sortBy(list, 'author'),
    COMMENTS: list => sortBy(list, 'num_comments').reverse(),
    POINTS: list => sortBy(list, 'points').reverse()
}

class Table extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sortKey: 'NONE',
            isSortReverse: false
        }
        this.onSort = this.onSort.bind(this)
    }

    onSort(sortKey) {
        const isSortReverse = this.state.sortKey === sortKey && !this.state.isSortReverse
        this.setState({sortKey, isSortReverse})
    }

    render() {
        console.log('Table-----props===:', this.props)
        const {list, onClick} = this.props
        const {sortKey,isSortReverse} = this.state
        const sortedList = SORTS[sortKey](list)
        const reverseSortedList = isSortReverse ? sortedList.reverse() : sortedList
        return (
            <div>
                <span style={{display: 'inline-block', width: '15%', textAlign: 'center'}}>
                    <Sort activeSortKey={sortKey} onSort={this.onSort} sortKey={'TITLE'}>作者</Sort>
                </span>
                <span style={{display: 'inline-block', width: '20%', textAlign: 'center'}}>
                    <Sort activeSortKey={sortKey} onSort={this.onSort} sortKey={'AUTHOR'}>标题</Sort>
                </span>
                <span style={{display: 'inline-block', width: '10%', textAlign: 'center'}}>
                    <Sort activeSortKey={sortKey} onSort={this.onSort} sortKey={'COMMENTS'}>评论</Sort>
                </span>
                <span style={{display: 'inline-block', width: '10%', textAlign: 'center'}}>
                    <Sort activeSortKey={sortKey} onSort={this.onSort} sortKey={'POINTS'}>点赞</Sort>
                </span>
                {reverseSortedList.map(item =>
                    <div className='App-datalist' key={item.objectID}>
                        <span>{item.author}</span>
                        <span><a href={item.url}>{item.title}</a></span>
                        <span>{item.num_comments}</span>
                        <span>{item.points}</span>
                        <Button onClick={() => {
                            onClick(item.objectID)
                        }}>删除</Button>
                    </div>
                )}
            </div>
        )

    }
}

Table.propTypes = {
    list: PropTypes.array.isRequired,
    onDismiss: PropTypes.func.isRequired
}
export default Table